//
//  LoginVC_new.m
//  Cunli
//
//  Created by ZhanyaaLi on 15/12/17.
//  Copyright © 2015年 lilubin. All rights reserved.
//

#import "LoginVC_new.h"
#import "SectionLineView.h"
#import "RegisterTableVC.h"
#import "NSString+MD5.h"
#import "MyDataService.h"
#import "Config.h"
#import "FindPwdStepTableVC1.h"
#import "CompleteDataTableVC.h"
//#import "MyVillageIntroVC.h"
#import "BaseUser.h"
#import "DetailUser.h"
#import "Login.h"
#import "MainTabbarVC.h"
#import "MMDrawerController.h"
#import "SidePersonMenuVC.h"

typedef NS_ENUM(int, ButtonActionType)
{
    ButtonActionTypeForget = 1000,       //忘记密码
    ButtonActionTypeLogin = 1001,        //登录
    ButtonActionTypeRegiste = 1002       //注册
};


#define KCLLOGINCHANGE @"myloginchange"
#define KCLPORTRAITCHANGE @"portraitChanged"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
//#define ButtonTag 1000

@interface LoginVC_new () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
{
    UITableView *_tableView;
    CGFloat _headerHeight;     //顶部headerView高度
    CGFloat _footerHeight;     //底部footerView高度
    CGFloat _startXPoint;      //控件起始x坐标
    CGFloat _kitWidth;         //控件宽度
    MBProgressHUD *_hud;
    NSString *_userName;       //用于保存用户名输入框的内容
    NSString *_userPassword;   //用于保存密码输入框的内容
}

@end

@implementation LoginVC_new

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initGlobalParams];
    [self initLoginTableView];
    [self createTableHeadAndFooterView];
    [self addTapRecoginzer];
    
    if (_netCheck.length != 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"登录失败" message:@"登录失败，请检查网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initGlobalParams
{
    _headerHeight = kScreenHeight * 1.0 / 2 - 40;
    _footerHeight = kScreenHeight - 180 - _headerHeight - 10;
    _startXPoint = kScreenWidth * 1.0 / 10;
    _kitWidth = kScreenWidth * 4.0 / 5;
}

- (void)initLoginTableView
{
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.bounces = NO;
    [_tableView setBackgroundColor:[UIColor whiteColor]];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:_tableView];
}

- (void)createTableHeadAndFooterView
{
    CGFloat headerImgStartY = _headerHeight / 3.0;
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, _headerHeight)];
    headerView.backgroundColor = [UIColor whiteColor];
//    CGFloat logoWidth = _kitWidth * 2.0 / 5.0;
//    CGFloat _logoStartX = kScreenWidth * 1.0 / 2.0 - logoWidth / 2.0;
    UIImageView *logoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_startXPoint, headerImgStartY, _kitWidth, _kitWidth * 2.0 / 5.0)];
    [logoImageView setImage:[UIImage imageNamed:@"切图1.png"]];
    [headerView addSubview:logoImageView];
    _tableView.tableHeaderView = headerView;
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, _footerHeight)];
    footerView.backgroundColor = [UIColor whiteColor];
    UIButton *registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registerBtn.tag = ButtonActionTypeRegiste;
    [registerBtn setFrame:CGRectMake(_startXPoint+10, _footerHeight-40, _kitWidth-20, 30)];
    [registerBtn setTitleColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"NavigationBgImage"]] forState:UIControlStateNormal];
    [registerBtn addTarget:self action:@selector(BtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [registerBtn setTitle:@"还没有账号？立即注册" forState:UIControlStateNormal];
    [registerBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
//    registerBtn.layer.cornerRadius = 5;
//    registerBtn.layer.masksToBounds = YES;
    
    [footerView addSubview:registerBtn];
    _tableView.tableFooterView = footerView;
}

- (void)addTapRecoginzer
{
    self.view.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignTheKeyboard)];
    [self.view addGestureRecognizer:tap];
}

- (void)resignTheKeyboard
{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        _tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }];
}


#pragma mark - UITableViewDelegate && UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [UITableViewCell new];
    if (indexPath.row == 0) {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(_startXPoint, 5, _kitWidth, 40)];
//        [textField setBackgroundColor:[UIColor orangeColor]];
        textField.placeholder = @"手机号 ";
        textField.tag = 2001;
        textField.delegate = self;
        [cell.contentView addSubview:textField];
        textField.keyboardType = UIKeyboardTypePhonePad;
        SectionLineView *lineView = [[SectionLineView alloc] initWithFrame:CGRectMake(_startXPoint-13, 45, _kitWidth+26, 3)];
        [lineView setBackgroundColor:[UIColor whiteColor]];
        [cell.contentView addSubview:lineView];
    }
    else if(indexPath.row == 1)
    {
        UITextField *textField2 = [[UITextField alloc] initWithFrame:CGRectMake(_startXPoint, 5, _kitWidth, 40)];
        textField2.placeholder = @"密码 ";
//        [textField2 setBackgroundColor:[UIColor greenColor]];
        textField2.tag = 2002;
        textField2.delegate = self;
        textField2.secureTextEntry = YES;
        [cell.contentView addSubview:textField2];
        
        SectionLineView *lineView = [[SectionLineView alloc] initWithFrame:CGRectMake(_startXPoint-13, 45, _kitWidth+26, 3)];
        [lineView setBackgroundColor:[UIColor whiteColor]];
        [cell.contentView addSubview:lineView];
    }
    else if(indexPath.row == 2)
    {
        UIButton *forgetPwdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [forgetPwdBtn setFrame:CGRectMake(kScreenWidth * 1.0 / 2, 0, _kitWidth * 1.0 / 2, 21)];
        forgetPwdBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        forgetPwdBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
        [forgetPwdBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [forgetPwdBtn setTitle:@"忘记密码？" forState:UIControlStateNormal];
        forgetPwdBtn.tag = ButtonActionTypeForget;
        [forgetPwdBtn setTitleColor:[UIColor colorWithHexString:InfoCellIntroduceColorValue] forState:UIControlStateNormal];
//        cell.backgroundColor = [UIColor redColor];
        [forgetPwdBtn addTarget:self action:@selector(BtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:forgetPwdBtn];
    }
    else
    {
        UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        loginBtn.tag = ButtonActionTypeLogin;
        [loginBtn setFrame:CGRectMake(_startXPoint, 5, _kitWidth, 40)];
        [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [loginBtn setBackgroundImage:[UIImage imageNamed:@"NavigationBgImage"] forState:UIControlStateNormal];
        [loginBtn addTarget:self action:@selector(BtnAction:) forControlEvents:UIControlEventTouchUpInside];
        loginBtn.layer.cornerRadius = 2;
        loginBtn.layer.masksToBounds = YES;

        [cell.contentView addSubview:loginBtn];
    }
//    [cell.textLabel setText:@"TextLabel"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 2) {
        return 30;
    }
    return 50;
}

#pragma mark - Button Action 忘记密码，登录，注册
- (void)BtnAction:(UIButton *)button
{
    [self resignTheKeyboard];
    switch (button.tag) {
        case ButtonActionTypeForget: //跳入找回密码界面
        {
//            NSLog(@"Forget action");
            FindPwdStepTableVC1 *findpwdVC = [[FindPwdStepTableVC1 alloc] init];
            if (_userName.length != 0) {
                findpwdVC.userName = _userName;
            }
            findpwdVC.modalPresentationStyle = UIModalPresentationFullScreen;
            findpwdVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [self presentViewController:findpwdVC animated:YES completion:NULL];
            break;
        }
        case ButtonActionTypeLogin:  //执行登录
        {
//            NSLog(@"Login action");
            [self loginAction];
            break;
        }
        case ButtonActionTypeRegiste: //跳入注册界面
        {
//            NSLog(@"Registe action");
            RegisterTableVC *registerVC = [[RegisterTableVC alloc] init];
            registerVC.modalPresentationStyle = UIModalPresentationFullScreen;
            registerVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            [self presentViewController:registerVC animated:YES completion:NULL];
            break;
        }
        default:
            break;
    }
}
- (void)loginAction
{
    if (_userName.length != 11) {
        [Config showHUDWithText:@"用户名错误" andImage:@"error"];
        return;
    }
    
    if (_userPassword.length < 6) {
        [Config showHUDWithText:@"密码错误" andImage:@"error"];
        return;
    }
    
//    [self resignTheKeyboard];
    
    _hud = [[MBProgressHUD alloc] initWithView:self.view];
    _hud.detailsLabelFont = [UIFont boldSystemFontOfSize:16];
    [self.view addSubview:_hud];
    [_hud show:YES];
    _hud.labelText = @"正在登录...";
    _hud.userInteractionEnabled = NO;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:3];
    [params setObject:_userName forKey:@"username"];
    [params setObject:_userPassword forKey:@"password"];
    [params setObject:@"1" forKey:@"appkey"];
    [params setObject:@"1" forKey:@"os"];
    [params setObject:@"1" forKey:@"udid"];
    [params setObject:@"1" forKey:@"osversion"];
    [params setObject:@"1" forKey:@"appversion"];
    [params setObject:[NSString getSignFromParam:params] forKey:@"sign"];
    
    //    NSLog(@"Login params:%@", params);
    [MyDataService requestURL:@"login.php" httpMethod:@"POST" params:params fileDatas:nil complection:^(id result) {
        [_hud hide:YES];
        NSLog(@"In LoginVC Login success:%@", result);
        if([[result objectForKey:@"response"] isEqualToString:@"login"])
        {
            [Login doLogin:result[@"userinfo"]];
            [Config saveUserPwd:_userPassword];
            [Config saveUserName:[Login curLoginBaseUser].username];
            [Config saveUserID:[Login curLoginBaseUser].userid];
            [Config saveLogintimes:[Login curLoginBaseUser].logintimes];
            NSDictionary *invitDic = [Login curLoginBaseUser].invit;
            [Config saveAutoLogin:YES];
            [self getUserDetailData];
            //登录成功，发送登录成功的消息
            if([[Login curLoginBaseUser].completed isEqualToString:@"Y"])
            {
                [self getUserDetailData];
                [self pushToMainVC];
            }
            else
            {
                CompleteDataTableVC *completeVC = [[CompleteDataTableVC alloc] init];
                completeVC.access_token = [Login curLoginBaseUser].usersession;
                completeVC.modalPresentationStyle = UIModalPresentationFullScreen;
                completeVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                completeVC.is_invint = invitDic[@"is_invint"];
                [self presentViewController:completeVC animated:YES completion:NULL];
            }
            
        }else
        {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *errorStr = [errorDic objectForKey:@"text"];
            [Config showHUDWithText:errorStr andImage:@"error"];
        }
    } failureAction:^{
        [_hud hide:YES];
        [Config showHUDWithText:@"登录失败" andImage:@"error"];
    }];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.5 animations:^{
        _tableView.frame = CGRectMake(0, -70, kScreenWidth, kScreenHeight);
    }];
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
//    NSLog(@"TextField.text:%@", textField.text);
    if (textField.tag == 2001) {
        _userName = textField.text;
    }
    else
    {
        _userPassword = textField.text;
    }
    return YES;
}

- (void)pushToMainVC
{
    MainTabbarVC *mainController = [[MainTabbarVC alloc] init];
    SidePersonMenuVC *sideMenuVC = [[SidePersonMenuVC alloc] init];
    MMDrawerController *drawerController = [[MMDrawerController alloc] initWithCenterViewController:mainController leftDrawerViewController:sideMenuVC];
    [drawerController setMaximumLeftDrawerWidth:LEFTSIDEWIDTH];
    [drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    [kkWindow setRootViewController:drawerController];
    [kkWindow makeKeyAndVisible];
}


- (void)getUserDetailData{
    
    NSMutableDictionary *CheckParams =[[NSMutableDictionary alloc] init];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"getinfo_member.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        NSLog(@"getinfo_member in appdelegate:%@",result);
//        NSDictionary *userInfoDic=[result objectForKey:@"userinfo"];
//        [Login saveUserDetailData:userInfoDic];
        [Login saveUserDetailData:result[@"userinfo"]];
        [[NSNotificationCenter defaultCenter] postNotificationName:KCLPORTRAITCHANGE object:@YES];
    }failureAction:^{
        
    }];
    [self loginOnEaseMob];
}

- (void)loginOnEaseMob{
    
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[Login curLoginBaseUser].huanxin_username password:[Login curLoginBaseUser].huanxin_password completion:^(NSDictionary *loginInfo, EMError *error) {
        if (!error && loginInfo) {
            NSLog(@">>>>>>>>>>>>>>>登陆成功<<<<<<<<<<<<<<<");
        }
    } onQueue:nil];
}


@end
